package com.js.service.bot.response;

import com.js.common.constant.BotConst;
import com.js.domian.entity.bot.ResponseEntity;
import com.js.domian.model.bot.ApiResult;
import com.js.domian.model.bot.BaseApi;
import com.js.domian.model.bot.analysis.MessageChain;
import com.js.domian.model.bot.support.SendGroupMsg;
import org.java_websocket.client.WebSocketClient;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public interface BaseService {
    MessageChain buildMessage(Long groupId, Long userId, String message, ResponseEntity response);

    default void sendGroupMessage(Long qq, Long groupId, MessageChain messageChain){
        BaseApi baseApi = new SendGroupMsg(groupId, messageChain);
        sendMessage(BotConst.webSocketClientMap.get(qq), baseApi);
    }

    default ApiResult sendMessage(WebSocketClient client, BaseApi baseApi) {
        client.send(baseApi.buildJson());
        CompletableFuture<ApiResult> completableFuture = new CompletableFuture<>();
        BotConst.completableFutureMap.put(baseApi.getEcho(), completableFuture);
        ApiResult apiResult = getApiResult(baseApi.getEcho());
        if (apiResult == null || !"ok".equals(apiResult.getStatus())) {
//            log.error(String.format("调用api出错: %s", apiResult));
        }
        return apiResult;
    }

    default ApiResult getApiResult(String echo) {
        CompletableFuture<ApiResult> completableFuture = BotConst.completableFutureMap.get(echo);
        ApiResult apiResult;
        while (true){
            try {
                if(!completableFuture.isDone()){
                    continue;
                }
                apiResult = completableFuture.get();
                BotConst.completableFutureMap.remove(echo);
                break;
            } catch (InterruptedException | ExecutionException e) {
//                log.error(e.getMessage(), e);
                return null;
            }
        }
        return apiResult;
    }
}
